<template>
  <div class="login-container">
    <el-tabs v-model="activeTab" type="card" stretch class="login-tabs">
      <!-- 账号登录 -->
      <el-tab-pane label="账号登录" name="account">
        <el-form ref="accountFormRef" :model="accountForm" :rules="accountRules" label-width="80px">
          <el-form-item label="用户名" prop="account">
            <el-input v-model="accountForm.account" />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="accountForm.password" show-password />
          </el-form-item>
          <el-form-item label="验证码" prop="code">
            <el-input v-model="accountForm.code" style="width: calc(100% - 120px)" />
            <img :src="captchaImage" alt="验证码" @click="refreshCaptcha" style="width: 100px; height: 40px; vertical-align: middle; margin-left: 10px; cursor: pointer;" />
          </el-form-item>

          <el-form-item>
            <el-button @click="onCancel">取消</el-button>
            <el-button type="primary" :disabled="isButtonDisabled"
                       icon="el-icon-user-solid" @click="submitAccountForm">登录</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <!-- 手机登录 -->
      <el-tab-pane label="手机登录" name="phone">
        <el-form ref="phoneFormRef" :model="phoneForm" :rules="phoneRules" label-width="80px">
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="phoneForm.mobile" />
          </el-form-item>
          <el-form-item label="短信码" prop="smsCode">
            <el-input v-model="phoneForm.smsCode" style="width: calc(100% - 120px)" />
            <el-button @click="sendSmsCode" :disabled="sending">{{ sendText }}</el-button>
          </el-form-item>
          <el-form-item label="验证码" prop="code">
            <el-input v-model="phoneForm.code" style="width: calc(100% - 120px)" />
            <img :src="captchaImage" alt="验证码" @click="refreshCaptcha" style="width: 100px; height: 40px; vertical-align: middle; margin-left: 10px; cursor: pointer;" />
          </el-form-item>

          <el-form-item>
            <el-button @click="onCancel">取消</el-button>
            <el-button type="primary" @click="submitPhoneForm">登录</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted} from 'vue'
import { ElMessage } from 'element-plus'
import axios from "axios";
import router from "@/router/index.js";

//pinia使用
import { userStore } from '@/store/index.js'
const userItemStore = userStore();


//登陆按钮不可用
const isButtonDisabled = ref(false);

// 账号登陆提交方法
function submitAccountForm() {
  accountFormRef.value.validate(valid => {
    if (valid) {
      axios.post("/user/login",accountForm).then(resp => {
        const user= resp.data;
        // 这里响应头大小写敏感，要写成小写
        localStorage.setItem('token', resp.headers['authorization']);
        // 保存用户信息，转成字符串保存
        localStorage.setItem('user', JSON.stringify(user));

        //存储用户
        userItemStore.updateUser(user)
        console.log(user)
        //修改状态
        userItemStore.updateLoginStatus(true)
        console.log(true)

        // 提示登录成功
        ElMessage({
          message:`登录成功，欢迎您：${user.account}！`,
          type:'success'
        });
        router.push("/getBookType?id=0");
      }).catch(error => {
        ElMessage.error(error.response.data);
      })
      
      //让登录按钮变得不可用
      isButtonDisabled.value = true
      // 5秒后变得可用
      setTimeout(() => {
        isButtonDisabled.value = false;
      }, 5000);
    }
  })
}

//手机号码登陆提交
function submitPhoneForm() {
  phoneFormRef.value.validate(valid => {
    if (valid) {
      axios.post("/user/smsLogin",phoneForm).then(resp => {
        const user= resp.data;
        // 这里响应头大小写敏感，要写成小写
        localStorage.setItem('token', resp.headers['authorization']);
        // 保存用户信息，转成字符串保存
        localStorage.setItem('user', JSON.stringify(user));

        //存储用户
        userItemStore.updateUser(user)
        console.log(user)
        //修改状态
        userItemStore.updateLoginStatus(true)
        console.log(true)

        // 提示登录成功
        ElMessage({
          message:`登录成功，欢迎您：${user.account}！`,
          type:'success'
        });
        router.push("/getBookType?id=0");
      }).catch(error => {
        ElMessage.error(error.response.data);
      })
    }
  })
}

// 当前激活的 tab
const activeTab = ref('account');

// 表单引用
const accountFormRef = ref(null)

const phoneFormRef = ref(null)

// 验证码图片
const captchaImage = ref(generateCaptcha())

function generateCaptcha() {
  axios.get(`/user/code`).then((response) => {
    captchaImage.value = response.data.base64Img;
    accountForm.key=response.data.key;
    phoneForm.key=response.data.key;
  })


  // const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
  // let code = ''
  // for (let i = 0; i < 4; i++) {
  //   code += chars.charAt(Math.floor(Math.random() * chars.length))
  // }
  // return `https://fake-captcha.com?text=${code}&bg=white&color=black`
}

function refreshCaptcha() {
  captchaImage.value = generateCaptcha()
}

// 表单数据
const accountForm = reactive({
  account: '',
  password: '',
  code: '',
  key:''
})

const phoneForm = reactive({

})

// 倒计时相关
const sending = ref(false)
const sendText = ref('发送验证码')
let countdown = 30

function sendSmsCode() {
  if (!phoneForm.mobile) {
    ElMessage.warning('请输入手机号')
    return
  }
  // 模拟发送验证码
  axios.get(`/user/sendSms/${phoneForm.mobile}`).then((response) => {
    ElMessage.success(response.data)
  }).catch(error => {
    ElMessage.error(error.response.data);
  }).finally(()=>{
    sending.value = true
    const timer = setInterval(() => {
      countdown--
      sendText.value = `${countdown}s`
      if (countdown <= 0) {
        clearInterval(timer)
        sending.value = false
        sendText.value = '重新发送'
        countdown = 30
      }
    }, 1000)
  })
}

// 表单验证规则
const validatePhone = (rule, value, callback) => {
  const reg = /^1[3-9]\d{9}$/
  if (!reg.test(value)) {
    callback(new Error('请输入正确的手机号'))
  } else {
    callback()
  }
}

const accountRules = {
  account: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 15, message: '长度在3到15个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 3, message: '至少6位', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 4, message: '验证码为4位', trigger: 'blur' }
  ]
}

const phoneRules = {
  mobile: [
    { required: true, validator: validatePhone, trigger: 'blur' },
    { len: 11, message: '手机号码为11位', trigger: 'blur' }
  ],
  smsCode: [
    { required: true, message: '请输入短信验证码', trigger: 'blur' },
    { len: 4, message: '短信验证码为4位', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 4, message: '验证码为4位', trigger: 'blur' }
  ]
}



function onCancel() {
  ElMessage.info('已取消')
  router.push('/')
}
onMounted(()=>{
  generateCaptcha();
})


</script>

<style scoped>
.login-container {
  width: 600px;
  margin: 100px auto;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.login-tabs {
  width: 100%;
}
</style>